package com.lemon.rule.express.instruction.op;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.lemon.rule.express.InstructionSetContext;
import com.lemon.rule.express.OperateData;

public class OperatorIf extends OperatorBase {

    private static final Logger logger = LoggerFactory.getLogger(OperatorIf.class);

    public OperatorIf(String aName) {
        this.name = aName;
    }

    public OperatorIf(String aAliasName, String aName, String aErrorInfo) {
        this.name = aName;
        this.aliasName = aAliasName;
        this.errorInfo = aErrorInfo;
    }

    public OperateData executeInner(InstructionSetContext parent, OperateData[] list) throws Exception {
        if (list.length < 2) {
            throw new Exception("\"" + this.aliasName + "\"操作至少要两个操作数");
        }
        logger.info(JSON.toJSONString(list));
        Object obj = list[0].getObject(parent);
        if (obj == null) {
            throw new Exception("\"" + this.aliasName + "\"的判断条件不能为空");
        } else if ((obj instanceof Boolean) == false) {
            throw new Exception(String.format("\"%s\"的判断条件 必须是 Boolean,不能是：%s", this.aliasName, obj.getClass().getName()));
        } else {
            if (((Boolean) obj).booleanValue() == true) {
                return list[1];
            } else {
                if (list.length == 3) {
                    return list[2];
                }
            }
            return null;
        }
    }
}